<?php namespace PFT;
use LaneWeChat\Core\TemplateMessage;
use pft\Member\MemberAccount;

defined('IN_PFT') or exit('No permission resources.');
/**
 * Created by PhpStorm.
 * User: fusha_000
 * Date: 15-4-15
 * Time: 下午4:01
 */

class Terminal {

    private $db;
    private $soap;
    private $memberID;
    private $landId;

    const TERMINAL_SERVER = '117.27.151.26';

    const TERMINAL_CLOSE  = 1;//关闭终端
    const TERMINAL_OPEN   = 0;//启用终端

    const MODE_CREATE     = 0;
    const MODE_UPDATE     = 1;

    public function __construct(\PDO $db, \SoapClient $soap, $memberID, $landId=0)
    {
        $this->db       = $db;
        $this->soap     = $soap;
        $this->memberID = $memberID;
        $this->landId   = $landId;
    }

    /**
     * 终端数据写入去向配置
     *
     * @return int 0默认向终端服务器写入数据 1不写数据 2向指定服务器写入数据
     */
    public function GetConfig()
    {
        // ALTER TABLE uu_land ADD COLUMN terminal_type tinyint(1) not null;/*终端类型——针对产品0启用1不启用*/
        // ALTER TABLE pft_member_extinfo ADD COLUMN terminal_type tinyint(1) not null;/*终端类型——针对全局0启用1不启用*/
        if ($this->landId) {
            //指定产品配置
            $sql = "SELECT terminal_type FROM uu_land WHERE salerid={$this->landId} LIMIT 1";
        } else {
            //全局配置——针对供应商
            $sql = "SELECT terminal_type FROM pft_member_extinfo WHERE fid={$this->memberID} LIMIT 1";
        }
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetchColumn(0);
    }

    /**
     * 检测终端服务器是否正常,假设都正常
     *
     * @return bool
     */
    public function ChkTerminalServer()
    {
        $fp = fsockopen(self::TERMINAL_SERVER, 80, $errno, $errstr, 1);
        if (!$fp) {
            //发送微信通知
            //TODO::微信发送通知
            define('DEFAULT_WECHAT_APPID', 'wxd72be21f7455640d');//票付通公众号
            include '/var/www/html/wx/wechat/iwx.php';
            $wx_open_id  = 'oNbmEuDdAEWDS_a02HYFlzNYFUTg';//CGP
            $data        = array(
                'first'       => array('value'=>'终端服务器连接异常！','color'=>'#173177'),
                'keyword1'    => array('value'=>'终端服务器连接异常;发布产品出现异常','color'=>'#173177'),
                'keyword2'    => array('value'=> '票付通的服务器','color'=>'#ff0000'),
                'keyword3'    => array('value'=> date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']),'color'=>'#ff0000'),
                'remark'      => array('value'=> "赶快找人看一看啊",'color'=>'#ff6600'),
            );

            TemplateMessage::sendTemplateMessage($data,$wx_open_id,
                TemplateMessage::TODO_WORK,'','#FF0000');
            return false;
        }
        fclose($fp);
        return true;
    }

    /**
     * 终端变更
     *
     * @param $terminal_type
     * @return bool
     */
    public function TerminalChange($terminal_type, $id=0)
    {
        $id   = $id>0 ? $id : $this->landId;
        $sql  = "UPDATE uu_land SET terminal_type=$terminal_type WHERE id=$id LIMIT 1";
//        echo $sql;
        $stmt = $this->db->prepare($sql);
        //array($terminal_type, $id)
        if ( $stmt->execute()===true) {
            //TODO::记录操作日志
//            echo 'ok';
            $mark = "修改终端设置|景区ID:{$id}|操作人ID:{$_SESSION['memberID']}";
            \AccessRecord::insert(\AccessRecord::ACTION_MODIFY_TERMINAL, $mark, $this->db);
        }
        if ($terminal_type==self::TERMINAL_OPEN) {
            //检查该景点是否有配置过终端
            $sql = "SELECT title,salerid,terminal FROM uu_land WHERE id=? LIMIT 1";
            $stmt = $this->db->prepare($sql);
            $stmt->execute(array( $id ));
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            //配置产品时未设置过终端
            if ( !$row['terminal'] ) {
                self::Write2Terminal($row['title'], $row['salerid']);
            }
        }
        return true;
    }

    /**
     * 终端类型全局设置
     *
     * @param $terminal_type
     * @return bool
     */
    public function GlobalTerminalChange($terminal_type, $apply_did=0)
    {
        //保存全局配置的参数，如果是管理员，就针对整个系统
        $sql = "UPDATE pft_member_extinfo SET terminal_type=? WHERE fid=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($terminal_type, $apply_did));
        //保存整个系统或该供应商的产品
        $where = $apply_did>1 ? "AND apply_did={$apply_did}" : '';
        $sql   = "UPDATE uu_land SET terminal_type=$terminal_type WHERE 1=1 $where AND terminal_type<>2";
        $stmt  = $this->db->prepare($sql);
        $res   = $stmt->execute();
        //保存全局配置
        return $res;
//        if ($all===true) {
//            $sql = "SELECT id FROM uu_land WHERE apply_did=? AND status<2 AND terminal_type<>2";
//            $stmt = $this->db->prepare($sql);
//            $stmt->execute(array($this->memberID));
//            $id_list = $stmt->fetchAll(\PDO::FETCH_COLUMN);
//            foreach ($id_list as $id) {
//                $this->TerminalChange($terminal_type, $id);
//            }
//        }
//        $args = array($terminal_type, $this->memberID);
//        print_r($args);
//        $sql = "UPDATE pft_member_extinfo SET terminal_type=? WHERE fid=? LIMIT 1";
//        echo $sql;
//        $stmt = $this->db->prepare($sql);
//        return $stmt->execute($args);
    }

    /**
     * 向远端服务器同步数据。该方法在创建产品时必须调用。
     * 添加/修改产品时，可以根据配置，选择是否向终端提交数据。
     *
     * @param $title
     * @param $salerid
     * @param int $mode
     * @param string $src_title
     * @param null $dlTxt
     * @return array
     */
    public function Write2Remote($title,$salerid,$mode=0,$src_title='', $dlTxt=NULL)
    {
        $res = array();
        $cfg = $this->GetConfig($this->memberID, $this->landId);
        switch ($cfg) {
            case 0:
                //默认，向终端提交数据
                self::Write2Terminal($title, $salerid, $mode,$src_title, $dlTxt);
                break;
            case 1:
                //用户配置，不向终端提交数据
                $res = array(
                    'status'=>'ok',
                    'msg'=>'',
                    'body'=>0
                );
                break;
            case 2:
                break;
            default:break;
        }
        return $res;
    }

    /**
     * 向终端写入数据
     *
     * @param string $title 产品名称
     * @param string $salerid 资源方6位数账号
     * @param int $mode 操作模式0写入1更新
     * @param string $src_title 所属产品名称
     * @param string $dlTxt 延迟验证
     * @return mixed
     */
    protected function Write2Terminal($title, $salerid, $mode=0, $src_title='',
                                      $dlTxt=NULL) {
        $title .= !empty($src_title) ? $src_title:'';
        if($mode==self::MODE_UPDATE) {
            if($dlTxt==NULL)$dlTxt='0|0';
            $res = $this->soap->Terminal_CFG_Update($title,$salerid,$dlTxt);
            if ($res!=100) {
                write_logs("UPDATE FAIL|title=$title,salerid=$salerid,mode=$mode,"
                    ."src_title=$src_title, dlTxt=$dlTxt",
                    '/var/www/html/new/d/logs/terminal_err.log');
            }
            return $res;
        }
        //echo  $salerid;
        $res = $this->soap->Terminal_CFG($title,$salerid,$dlTxt);
        if(strpos($res,'|')!==false) {
            $t_no = explode('|', $res);
            return array(
                'status' => 'ok',
                'msg'  => '生成终端号成功',
                'body' => $t_no[1]
            );
        }
        write_logs("CREATE FAIL|title=$title,salerid=$salerid,mode=$mode,"
                ."src_title=$src_title, dlTxt=$dlTxt",
                '/var/www/html/new/d/logs/terminal_err.log');
        return array(
            'status' => 'fail',
            'msg'  => $res,
            'body' => ''
        );
    }

}